import Vue from 'vue'
import Router from 'vue-router'
import cloneDeep from 'lodash/cloneDeep'
import store from '@/store'
import globalRouter from '@/router/global-router'
import mainRouter from '@/router/main-router'
import { getUserMenuApi } from '@/api/menu'

// 解决重复路由跳转bug，也可以直接将vue-router升级到3.0
Vue.use(Router)

// 开发环境不使用懒加载, 因为懒加载页面太多的话会造成webpack热更新太慢, 所以只有生产环境使用懒加载
const _import = require('./import-' + process.env.NODE_ENV)

const router = new Router({
  // 默认router的model为hash（地址栏#分割路由）
  model: 'hash',
  // 每次访问滚动条都置0
  scrollBehavior: () => ({ y: 0 }),
  // 是否已经添加动态（菜单）路由
  isAddDynamicMenuRoutes: false,
  routes: globalRouter.concat(mainRouter)
})

// 导航守卫-动态路由菜单
router.beforeEach((to, from, next) => {
  if (router.options.isAddDynamicMenuRoutes || currentRouteType(to) === 'global') {
    next()
  } else {
    getUserMenuApi().then(res => {
      addDynamicMenuRoute(res.data.userMenuInfoVos)
      router.options.isAddDynamicMenuRoutes = true
      store.commit('common/SET_MENUS', cloneDeep(res.data.userMenuInfoVos || []))
      store.commit('common/SET_PERMISSIONS', cloneDeep(res.data.permissions || []))
      // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
      next({...to, replace: false})
    })
  }
})

function currentRouteType(route) {
  for (let i = 0; i < globalRouter.length; i++) {
    if (route.path === globalRouter[i].path) {
      return 'global'
    }
  }
  return 'main'
}
/**
 * 添加动态(菜单)路由
 * @param {*} menus 菜单列表
 * @param {*} routes 递归创建的动态(菜单)路由
 */
function addDynamicMenuRoute(menus = [], routes = []) {
  let temp = []
  for (let i = 0; i < menus.length; i++) {
    let menu = menus[i]
    let subMenus = menu.subMenus
    if (subMenus && subMenus.length >= 1) {
      temp = temp.concat(subMenus)
    } else if (menu.url && /\S/.test(menu.url)) {
      menu.url = menu.url.replace(/^\//, '')
      let path = menu.url.replace(new RegExp('/', 'g'), '-')
      let route = {
        path: path,
        component: null,
        name: path,
        meta: {
          menuId: menu.id,
          title: menu.name,
          isDynamic: true,
          keepAlive: menu.keepAlive,
          isTab: menu.label,
          iframeUrl: '',
          type: 'view'
        }
      }
      if (menu.urlType === 1) {
        // url是https开头的通过iframeUrl展示
        route['path'] = `i-${menu.id}`
        route['name'] = `i-${menu.id}`
        route['meta']['iframeUrl'] = menu.url
        route['meta']['type'] = 'iframe'
      } else {
        // 同时获取子组件
        try {
          route['component'] = _import(`modules/${menu.url}`) || null
        } catch (e) {}
      }
      routes.push(route)
    }
  }
  if (temp.length >= 1) {
    addDynamicMenuRoute(temp, routes)
  } else {
    mainRouter.name = 'main-dynamic'
    mainRouter.children = routes
    router.addRoutes([
      mainRouter,
      { path: '*', redirect: { name: '404' } }
    ])
    store.dispatch('common/DynamicMenuRoutes', cloneDeep(mainRouter.children || []))
  }
}

export default router
